package com.ecloud.trend.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ecloud.common.util.RequestUtil;
import com.ecloud.trend.constant.RequestEnum;
import com.ecloud.trend.dao.TdbMapper;
import com.ecloud.trend.entities.TdbDaily;
import com.ecloud.trend.entities.TdbTag;
import com.ecloud.trend.service.TdbService;
import com.ecloud.trend.service.TrendService;
import com.ecloud.trend.vo.TdbEnvironmentPresentResult;
import com.ecloud.trend.vo.TdbPresentVo;
import com.ecloud.trend.vo.TrendDataVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Squbi
 */
@Service
public class TdbServiceImpl implements TdbService {

    @Autowired
    private TdbMapper tdbMapper;

    @Autowired
    private TrendService trendService;

    @Override
    public List<TdbDaily> yesterday() {
        return tdbMapper.selectYesterday();
    }

    @Override
    public List<TdbPresentVo> selectPresentEnergyData() {
        return selectPresentData(1);
    }

    @Override
    public List<TdbPresentVo> selectPresentControlData() {
        return selectPresentData(2);
    }

    private List<TdbPresentVo> selectPresentData(int tagTypeValue) {
        List<TdbTag> tdbTags = tdbMapper.selectTdbTags(tagTypeValue);
        List<TdbPresentVo> result = new ArrayList<>();

        int oneTimeTags = 500;
        for (int i = 0; i < tdbTags.size(); i += oneTimeTags) {
            int index = 0;
            int max = Math.min(i + oneTimeTags, tdbTags.size());
            String[] tagArr = new String[max - i];
            for (int j = i; j < max; j++) {
                tagArr[index] = tdbTags.get(j).getTagNumber();
                index++;
            }
            List<TrendDataVo> trendDataVos = trendService.lastValues(tagArr);
            index = 0;
            for (int j = i; j < max; j++) {
                result.add(new TdbPresentVo(tdbTags.get(j), trendDataVos.get(index)));
                index++;
            }
        }
        return result;
    }

    @Override
    public TdbEnvironmentPresentResult presentEnvironmentData() {
        String json = RequestUtil.sendPost(RequestEnum.ENVIRONMENT.toStr(), JSONObject.parseObject("{}"));
        return JSON.parseObject(json, TdbEnvironmentPresentResult.class);
    }
}
